#!/bin/sh /etc/rc.common
# Copyright (C) 2021 Tianling Shen <cnsztl@immortalwrt.org>

USE_PROCD=1
START=99

CONF="v2raya"
PROG="/usr/bin/v2raya"

is_enabled() {
	local enabled
	config_get enabled "$1" "$2" "${3:-0}"
	if [ "$enabled" -eq "1" ]; then
		return 0
	else
		return 1
	fi
}

append_param() {
	procd_append_param command "--$1" $2
}

append_param_arg() {
	local value
	config_get value "$1" "$2" $4
	[ -n "$value" ] && append_param "$3" "$value"
}

start_service() {
	config_load "$CONF"

	is_enabled "config" "enabled" || exit 1

	procd_open_instance "$CONF"
	procd_set_param command "$PROG"

	append_param_arg "config" "address" "address" "0.0.0.0:2017"
	append_param_arg "config" "config" "config" "/etc/v2raya"
	append_param_arg "config" "plugin_listen_port" "pluginlistenport" "32346"
	append_param_arg "config" "v2ray_bin" "v2ray-bin"
	append_param_arg "config" "v2ray_confdir" "v2ray-confdir"
	append_param_arg "config" "vless_grpc_inbound_cert_key" "vless-grpc-inbound-cert-key"
	is_enabled "config" "force_ipv6_on" && append_param "force-ipv6-on"
	is_enabled "config" "verbose" && append_param "verbose"

	procd_set_param limits core="unlimited"
	procd_set_param respawn

	procd_close_instance
}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger "$CONF"
}
